package me.liyin.flowabe.demo2;

import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Demo2 {

    /**
     * 初始化后的引擎对象
     */
    private ProcessEngine processEngine;


    @Before
    public void initEngine(){
        ProcessEngineConfiguration cfg = new StandaloneProcessEngineConfiguration()
                .setJdbcUrl("jdbc:mysql://192.168.1.30:3306/flowable?autoReconnect=true&serverTimezone=Asia/Shanghai")
                .setJdbcUsername("liyin")
                .setJdbcPassword("iToPXMkwU8SfHcJ")
                .setJdbcDriver("com.mysql.jdbc.Driver")
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);

         this.processEngine = cfg.buildProcessEngine();
    }

    @Test
    public void deployABpm() {
        RepositoryService repositoryService = processEngine.getRepositoryService();
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("holiday-request.bpmn20.xml")
                .deploy();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deployment.getId())
                .singleResult();

        log.info("Found process definition[{}]",processDefinition.getName());
    }

    @Test
    public void startProcess() {
        RuntimeService runtimeService = processEngine.getRuntimeService();

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("employee", "Liyin");
        variables.put("nrOfHolidays", 7);
        variables.put("description", "2025蛇年春节，回家过年啦！");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("holidayRequest", variables);
        log.info("请假流程[{}][{}]已提交完成，请等待审批。",processInstance.getName(),processInstance.getProcessInstanceId());

    }

    @Test
    public void completeTask() {

        TaskService taskService = processEngine.getTaskService();

        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list();
        log.info("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            log.info(") task name[{}]",tasks.get(i).getName());
        }

        log.info("Which task would you like to complete ?");
        Task task = tasks.get(0);
        Map<String, Object> processVariables = taskService.getVariables(task.getId());
        log.info("员工[{}] wants [{}] of holidays. Do you approve this?",processVariables.get("employee"),processVariables.get("nrOfHolidays"));

        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("approved", true);
        taskService.complete(task.getId(), variables);
    }

    @Test
    public void completeUserTask() {

        TaskService taskService = processEngine.getTaskService();

        List<Task> tasks = taskService.createTaskQuery().taskAssignee("Liyin").list();
        log.info("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            log.info(") task name[{}]",tasks.get(i).getName());
        }

        log.info("Which task would you like to complete ?");
        Task task = tasks.get(0);
        Map<String, Object> processVariables = taskService.getVariables(task.getId());
        log.info("员工[{}] wants [{}] of holidays. Do you approve this?",processVariables.get("employee"),processVariables.get("nrOfHolidays"));

        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("approved", true);
        taskService.complete(task.getId(), variables);
    }

    @Test
    public void listHistoryInstance(){
        HistoryService historyService = processEngine.getHistoryService();
        List<HistoricActivityInstance> activities =
                historyService.createHistoricActivityInstanceQuery()
                        .processInstanceId("2504")
                        .finished()
                        .orderByHistoricActivityInstanceEndTime().asc()
                        .list();

        for (HistoricActivityInstance activity : activities) {
            log.info("activityId[{}] took [{}] milliseconds",activity.getActivityId(),activity.getDurationInMillis());
        }
    }
}
